package com.sp.scmdb.serviceImpl;

import java.util.List;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sp.scmdb.bean.LogBean;
import com.sp.scmdb.bean.UserBean;
import com.sp.scmdb.common.CommonParamter;
import com.sp.scmdb.dao.LogDao;
import com.sp.scmdb.entity.Log;
import com.sp.scmdb.service.LogService;

@Service("logService")
public class LogServiceImpl implements LogService {

	private LogDao logDao;

	/**
	 * @param logDao
	 *            the logDao to set
	 */
	@Autowired
	public void setLogDao(LogDao logDao) {
		this.logDao = logDao;
	}

	@SuppressWarnings("unchecked")
	public LogBean findAll(LogBean logBean, LogBean oldLogBean) {
		List<Log> listLog = null;
		if (logBean.equals(oldLogBean)) {
			listLog = oldLogBean.getAllList();
		} else {

			StringBuffer sb = new StringBuffer();
			sb.append("from Log where 1=1");
			if (StringUtils.isNotEmpty(logBean.getUserName())) {
				sb.append(" and  nameUser = '" + logBean.getUserName() + "' ");
			}
			if (StringUtils.isNotEmpty(logBean.getStartTime())) {
				sb.append("  and dtOperation  >= '"
						+ logBean.getStartTime().toString() + "'  ");
			}
			if (StringUtils.isNotEmpty(logBean.getEndTime())) {
				sb.append("  and dtOperation  <= '"
						+ logBean.getEndTime().toString() + "'  ");
			}
			listLog = logDao.queryHql(sb.toString()+" order by dtOperation ");

		}
		if (CollectionUtils.isNotEmpty(listLog)) {
			logBean.setAllList(listLog);
			logBean.setList(listLog.subList(logBean.getCurrentRow(), logBean
					.getLastRow()));
		}
		return logBean;
	}

	@Transactional
	public String addLog(UserBean t, String message) {
		String result = "3";
		Log log = new Log();
		log.setNameUser(t.getUserName());
		log.setOperation(message);
		log.setDtOperation(new DateTime());
		if (log != null) {
			logDao.save(log);
			result = CommonParamter.CHECK_SUCCESS;
		}
		return result;
	}
}
